package com.btpj.module_search.ui

import androidx.lifecycle.viewModelScope
import androidx.paging.DataSource
import androidx.paging.PageKeyedDataSource
import com.btpj.jetpack.base.BaseListViewModel
import com.btpj.jetpack.entity.DataBean
import com.btpj.jetpack.utils.ToastUtil
import com.btpj.jetpack.entity.ApiResult
import com.btpj.module_search.data.remote.SearchRepository
import kotlinx.coroutines.launch
import java.util.*

class SearchResultViewModel(private val repository: SearchRepository) :
    BaseListViewModel<DataBean>() {

    private var mHotKey: String = ""

    fun setHotKey(hotKey: String) {
        mHotKey = hotKey
    }

    override fun createDataSource(): DataSource<Int, DataBean> {
        return object : PageKeyedDataSource<Int, DataBean>() {
            override fun loadInitial(
                params: LoadInitialParams<Int>,
                callback: LoadInitialCallback<Int, DataBean>
            ) {
                loadData(0, callback)
            }

            override fun loadAfter(params: LoadParams<Int>, callback: LoadCallback<Int, DataBean>) {
                loadDataAfter(params.key, callback)
            }

            override fun loadBefore(
                params: LoadParams<Int>,
                callback: LoadCallback<Int, DataBean>
            ) {
                callback.onResult(Collections.emptyList(), null)
            }

        }
    }

    private fun loadData(
        page: Int,
        callback: PageKeyedDataSource.LoadInitialCallback<Int, DataBean>
    ) {
        viewModelScope.launch {
            when (val result = repository.search(page, mHotKey)) {
                is ApiResult.Success -> callback.onResult(result.data.datas, null, 1)
                is ApiResult.Error -> ToastUtil.showShort(result.exception.errorMsg ?: "请求失败")
            }
        }
    }


    fun loadDataAfter(
        key: Int,
        callback: PageKeyedDataSource.LoadCallback<Int, DataBean>
    ) {

        viewModelScope.launch {
            when (val result = repository.search(key, mHotKey)) {
                is ApiResult.Success -> callback.onResult(result.data.datas, key + 1)
                is ApiResult.Error -> ToastUtil.showShort(result.exception.errorMsg ?: "请求失败")
            }
        }
    }
}